<style lang="less">
    @import "../../../../styles/common.less";
</style>
<template>
    <div>
        <Card dis-hover :bordered="false">
            <Row style="margin-bottom: 20px;">
                <Button v-bind:disabled="cannotAdd" type="primary" icon="plus-round" @click="handleAdd(1)">添加</Button>
                <Button type="success" icon="edit" @click="handleAdd(2)">编辑</Button>
                <Poptip confirm
                        title="您确认要删除选中的记录么？"
                        @on-ok="handleDelete"
                        ok-text="确认"
                        placement="right-start"
                        cancel-text="取消">
                    <Button type="error" icon="android-remove" v-bind:disabled="cannotDelete">删除</Button>
                </Poptip>
            </Row>
            <Row :gutter="10">
                <Col :md="24" :lg="6">
                    <Input ref="searchFrom" type="text" v-model="keyWord" placeholder="输入关键字进行过滤" @on-enter="searchByKey">
                    </Input>
                    <Card dis-hover>
                        <Tree :data="treeData"
                            @on-select-change="handleselectchange"></Tree>
                    </Card>
                </Col>
                <Col :md="24" :lg="18">
                    <Card dis-hover>
                        <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="80" inline>
                            <Row>
                                <Col span="8">
                                <FormItem label="菜单名称" prop="name" class="form-item">
                                    <Input v-bind:disabled="connotEdit" v-model="formItem.name" placeholder="请输入名称">
                                    </Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="资源类型" prop="resourceType" class="form-item">
                                    <Select v-bind:disabled="selectType" v-model="formItem.resourceType" placeholder="请选择" @on-change="handleTypeChange">
                                        <Option v-for="item in menuTypeList" :value="item.value" :key="item.label">{{ item.label }}</Option>
                                    </Select>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="组件名称" prop="component" class="form-item">
                                    <Input v-bind:disabled="connotEdit || isSelectMenu" v-model="formItem.component" placeholder="请输入组件名称">
                                    </Input>
                                </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span="8">
                                <FormItem label="资源路径" prop="url" class="form-item">
                                    <Input v-bind:disabled="connotEdit" v-model="formItem.url" placeholder="请输入资源路径">
                                    </Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="路由名称" prop="routerName" class="form-item">
                                    <Input v-bind:disabled="connotEdit" v-model="formItem.routerName" placeholder="请输入路由名称">
                                    </Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="是否显示" prop="isShow" class="form-item">
                                    <Select v-bind:disabled="connotEdit" v-model="formItem.isShow" placeholder="请选择">
                                        <Option v-for="item in isShowList" :value="item.value" :key="item.label">{{ item.label }}</Option>
                                    </Select>
                                </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span="8">
                                <FormItem label="权限标识" prop="permission" class="form-item">
                                    <Input v-bind:disabled="connotEdit" v-model="formItem.permission" placeholder="请输入权限标识">
                                    </Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="菜单备注" prop="remarks" class="form-item">
                                    <Input v-bind:disabled="connotEdit" v-model="formItem.remarks" placeholder="请输入备注">
                                    </Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="图标" prop="icon" class="form-item">
                                    <Input v-bind:disabled="connotEdit" v-model="formItem.icon" placeholder="请输入图标">
                                    </Input>
                                </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem>
                                    <Button v-bind:disabled="readonly" type="primary" icon="checkmark-round" @click="saveMenu">保存</Button>
                                    <Button v-bind:disabled="readonly" type="error" icon="close-round" style="margin-left: 20px;" @click="handleCancel">取消</Button>
                                </FormItem>
                            </Row>
                        </Form>
                    </Card>
                    <Card dis-hover style="border-top: none;">
                        <p slot="title">按钮或资源</p>
                        <Form :model="resourceForm" inline>
                            <FormItem>
                                <Input v-model="resourceForm.resourceName" icon="ios-search-strong" placeholder="资源名称" @keydown.enter="searchRes" @on-click="searchRes">
                                </Input>
                            </FormItem>
                            <FormItem>
                                <Button type="primary" icon="plus-round" @click="handleAddRes">添加</Button>
                                <Button type="success" icon="edit" @click="handleEditRes">编辑</Button>
                                <Poptip confirm
                                        title="您确认要删除选中的记录么？"
                                        @on-ok="delResource"
                                        ok-text="确认"
                                        placement="right-start"
                                        cancel-text="取消">
                                    <Button type="error" icon="android-remove" >删除</Button>
                                </Poptip>
                            </FormItem>
                        </Form>
                        <Table border
                               type="edit"
                               highlight-row
                               ref="currentRowTable"
                               :loading="is_loading"
                               :columns="DataColumns"
                               :data="tableData"
                               @on-current-change="handleRowChange"></Table>
                    </Card>
                </Col>
            </Row>
        </Card>
        <Modal
                title="添加资源"
                v-model="addResource"
                ok-text="保存"
                :closable="false"
        >
            <Form ref="resFormItem" :model="resFormItem" :rules="resValidate" :label-width="80" inline>
                <Row>
                    <Col span="12">
                    <FormItem label="资源名称" prop="name">
                        <Input style="width: 150px" v-model="resFormItem.name" placeholder="请输入名称">
                        </Input>
                    </FormItem>
                    </Col>
                    <Col span="12">
                    <FormItem label="是否显示" prop="isShow">
                        <Select style="width: 150px" v-model="resFormItem.isShow" placeholder="请选择">
                            <Option v-for="item in isShowList" :value="item.value" :key="item.label">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="12">
                        <FormItem label="资源类型" prop="resourceType">
                            <Select style="width: 150px" v-model="resFormItem.resourceType" placeholder="请选择">
                                <Option v-for="item in resTypeList" :value="item.value" :key="item.label">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="12">
                    <FormItem label="权限标识" prop="permission">
                        <Input style="width: 150px" v-model="resFormItem.permission" placeholder="请输入权限标识">
                        </Input>
                    </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="12">
                    <FormItem label="路由名称" prop="routerName">
                        <Input style="width: 150px" v-model="resFormItem.routerName" placeholder="请输入路由名称">
                        </Input>
                    </FormItem>
                    </Col>
                    <Col span="12">
                    <FormItem label="资源备注" prop="remarks">
                        <Input style="width: 150px" v-model="resFormItem.remarks" placeholder="请输入备注">
                        </Input>
                    </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" icon="checkmark-round" @click="saveRes">保存</Button>
                <Button type="error" icon="close-round" @click="cancelRes">取消</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
  import { fetchGetData,adminUrl } from '@/libs/fetch.js';
  import { fetchPostData,adminUrl } from '@/libs/fetch.js';
  import util from '@/libs/util.js';
  export default{
    data(){
      return {
        keyWord: '', //菜单搜索关键字
        treeData: [], //菜单数据
        allData: [], //存放菜单数据
        selectedMenu: [], //选中菜单节点
        formItem: {   //菜单信息form
          name: '',
          url: '',
          isShow: '',
          resourceType: '',
          component: '',
          permission: '',
          routerName: '',
          remarks: '',
          icon: ''
        },
        isShowList: [{
          value: 1,
          label: '是'
        },{
          value: 0,
          label: '否'
        }],
        menuTypeList: [{
          value: '0',
          label: '目录'
        },{
          value: '1',
          label: '菜单'
        }],
        resTypeList:[{
          value: '2',
          label: '按钮'
        },{
          value: '3',
          label: '资源'
        }],
        ruleValidate:{
          name: [{ required: true, message: '资源名称不能为空', trigger: 'blur'}],
          isShow: [{ type:'number', required: true, message: '是否显示不能为空', trigger: 'change'}],
          resourceType: [{ required: true, message: '资源类型不能为空', trigger: 'change'}],
          routerName: [{ required: true, message: '路由名称不能为空', trigger: 'blur'}],
          component: [{ required: true, message: '组件名称不能为空', trigger: 'blur'}],
          url: [{ required: true, message: '资源路径不能为空', trigger: 'blur'}]
        },
        resValidate:{
          name: [{ required: true, message: '资源名称不能为空', trigger: 'blur'}],
          isShow: [{ type:'number', required: true, message: '是否显示不能为空', trigger: 'change'}],
          resourceType: [{ required: true, message: '资源类型不能为空', trigger: 'change'}],
          permission: [{ required: true, message: '权限标识不能为空', trigger: 'blur'}],
          routerName: [{ required: true, message: '路由名称不能为空', trigger: 'blur'}]
        },
        cannotAdd: false, //菜单添加按钮是否可用
        cannotDelete: false, //菜单删除按钮是否可用
        isEdit: false, //true：修改菜单信息；false：添加菜单
        resourceForm: {  //资源搜索关键字
          resourceName: ''
        },
        is_loading: false, //表格loading
        DataColumns: [{
          title: '资源名称',
          key: 'name',
          align:'center'
        },{
          title: '是否显示',
          key: 'isShow',
          align:'center',
          render: (h, params) => {
            let flag = params.row.isShow == '1' ? '是' : '否';
            return h('div', flag);
          }
        },{
          title: '资源类型',
          key: 'resourceType',
          align:'center',
          render: (h, params) => {
            let type = '';
            if(params.row.resourceType == '0'){
              type = '目录';
            }else if(params.row.resourceType == '1'){
              type = '菜单';
            }else if(params.row.resourceType == '2'){
              type = '按钮';
            }else{
              type = '资源';
            }
            return h('div', type);
          }
        },{
          title: '权限标识',
          key: 'permission',
          align:'center'
        },{
          title: '路由名称',
          key: 'routerName',
          align: 'center'
        },{
          title: '备注',
          key: 'remarks',
          align: 'center'
        }],
        tableData: [],
        allTableData: [], //表格静态数据
        addResource: false,
        selectRowData:'',
        connotEdit: true, //编辑菜单信息时为false，可保存
        readonly: true, //编辑菜单信息时为false，可取消
        isSelectMenu: false, //资源类型为目录时，组件不可更改
        selectType: true, //资源类型是否可选
        resFormItem: {
          name: '',
          isShow: '',
          resourceType: '',
          permission: '',
          routerName: '',
          remarks: ''
        },
        isResEdit: false
      }
    },
    methods: {
      //加载树形菜单
      getTreeDataList(){
        fetchGetData(adminUrl+'/admin/menu/tree',{
        }).then(data=>{
          if(data.status==1){
            this.treeData = util.deepcopy(data.data);
            this.allData = data.data;
            this.$Loading.finish();
          }else{
            this.$Loading.error();
          }
        });
      },
      //选中菜单节点
      handleselectchange(selectMenu){
        this.selectedMenu = selectMenu;
        this.tableData = [];
        this.selectType = true;
        if(selectMenu.length > 0){
          //选中节点后，右侧展示信息（重置）
          this.resetFormItem();
          this.selectRowData = '';
          //若选中二级子节点，则添加按钮不可用，若选中根节点，则删除按钮不可用
          if(!selectMenu[0].isRoot){
            this.cannotAdd = true;
            this.cannotDelete = false;
          }else {
            this.cannotAdd = false;
            if(selectMenu[0].id == 0){
              this.cannotDelete = true;
            }
          }
          //获取菜单信息
          this.getMenuDetail();
        }else{
          this.resetFormItem();
          this.cannotAdd = false;
          this.cannotDelete = false;
        }
      },
      getMenuDetail(){
        this.$Loading.start();
        let menuId = this.selectedMenu[0].id;
        let url = adminUrl+'/admin/menu/detail/' + menuId;
        fetchGetData(url,{}).then(data=>{
          if(data.status==1){
            let formItem = data.data;
            this.formItem = formItem;
            let tableData = data.data.resources;
            if(tableData && !this.selectedMenu[0].isRoot){
              this.allTableData = tableData;
              this.tableData = tableData;
            }
            this.$Loading.finish();
          }else{
            this.$Loading.error();
          }
        });
      },
      //关键字搜索菜单
      searchByKey(){
        this.selectedMenu = [];
        let keyword = this.keyWord;
        let data = util.deepcopy(this.allData);
        if(keyword == ''){
          this.treeData = data;
        }else{
          for(var i=0; i<data.length; i++){
            if(data[i].children && data[i].children.length > 0){
              var childNodes = data[i].children;
              for(var j=0; j<childNodes.length; j++){
                if(childNodes[j].children && childNodes[j].children.length > 0){
                  var grandChildren = childNodes[j].children;
                  for(var s=0; s<grandChildren.length; s++){
                    if(grandChildren[s].title.indexOf(keyword) <= -1){
                      grandChildren.splice(s,1);
                      s--;
                    }
                  }
                  if(grandChildren.length == 0 && childNodes[j].title.indexOf(keyword) <= -1){
                    childNodes.splice(j,1);
                    j--;
                  }
                }
              }
              if(childNodes.length == 0 && data[i].title.indexOf(keyword) <= -1){
                data.splice(i,1);
                i--;
              }
            }
          }
          this.treeData = data;
        }
        this.cannotAdd = false;
        this.cannotDelete = false;
      },
      //点击添加/编辑按钮
      handleAdd(index){
        if(this.selectedMenu.length > 0){
          if(index == 1){
            this.isEdit = false;
            this.$refs['formItem'].resetFields();
            this.connotEdit = false;
            this.isSelectMenu = false;
          }else{
            this.$refs['formItem'].resetFields();
            this.getMenuDetail();
            this.isEdit = true;
            this.connotEdit = false;
            if(this.formItem.resourceType == '0'){
              this.isSelectMenu = true;
            }else{
              this.isSelectMenu = false;
            }
          }
          this.readonly = false;
        }else{
          this.$Message.error('请先选中菜单目录');
        }
      },
      //点击删除按钮
      handleDelete(){
        if(this.selectedMenu.length > 0){
          let id = this.selectedMenu[0].id;
          this.delMenuOrRes(id,'menu');
        }else{
          this.$Message.error('请选中要删除的记录');
        }
      },
      //选则资源类型为目录时，component为main且不可更改
      //一级目录下只能添加菜单
      handleTypeChange(selectType){
        if(!this.connotEdit){
          if(selectType == '0'){
            this.formItem.component = 'Main';
            this.isSelectMenu = true;
            if(this.isEdit){
              this.selectType = true;
            }
          }else if(!this.isEdit){
            if(this.selectedMenu[0].id != 0){
              this.formItem.resourceType = '1';
              this.formItem.component = '';
              this.selectType = true;
            }else{
              this.selectType = false;
            }
            this.formItem.component = '';
            this.isSelectMenu = false;
          }
        }
      },
      //添加菜单后保存
      saveMenu(){
        let formData = this.formItem;
        formData["type"] = formData.resourceType;
        formData["router"] = formData.routerName;
        this.$refs.formItem.validate((valid) => {
          if (valid) {
            this.$Loading.start();
            if(this.isEdit){
              formData["id"] = this.selectedMenu[0].id;
              this.updateMenuOrRes(formData, 'menu');
            }else{
              formData["parentId"] = this.selectedMenu[0].id;
              this.addMenuOrRes(formData, 'menu');
            }
          }
        });
      },
      //取消
      handleCancel(){
        this.handleselectchange(this.selectedMenu);
      },
      addMenuOrRes(formData, type){
        fetchPostData(adminUrl+'/admin/menu/add',formData)
          .then(data=>{
            if(data.status==1){
              if(type == 'menu'){
                this.getTreeDataList();
                this.resetFormItem();
              }else{
                this.cancelRes();
                this.handleselectchange(this.selectedMenu);
              }
              this.$Message.success('添加成功！');
              this.$Loading.finish();
            }else{
              this.$Message.error('保存失败！');
              this.$Loading.error();
            }
          });
      },
      //更新菜单后保存
      updateMenuOrRes(formData, type){
        fetchPostData(adminUrl+'/admin/menu/update',formData)
          .then(data=>{
            if(data.status==1){
              if(type != 'menu'){
                this.cancelRes();
              }
              this.handleselectchange(this.selectedMenu);
              this.$Message.success('更新成功！');
              this.$Loading.finish();
            }else{
              this.$Message.error('更新失败！');
              this.$Loading.error();
            }
          });
      },
      //初始化右侧信息form
      resetFormItem(){
        this.$refs['formItem'].resetFields();
        this.connotEdit = true;
        this.readonly = true;
      },
      delMenuOrRes(id,name){
        this.$Loading.start();
        let url = '/admin/menu/del/' + id;
        fetchPostData(adminUrl+url,{}).then(data=>{
          if(data.status==1){
            if(name == 'menu'){
              this.getTreeDataList(); //重新渲染菜单树
              this.resetFormItem();
            }else{
              this.handleselectchange(this.selectedMenu);   //重新渲染表格数据
            }
            this.$Message.success('删除成功！');
            this.$Loading.finish();
          }else{
            this.$Message.error('删除失败！');
            this.$Loading.error();
          }
        });
      },
      //选中表格的行
      handleRowChange (currentRow, oldCurrentRow) {
        this.selectRowData = currentRow;
      },
      //点击添加资源按钮
      handleAddRes(){
        if(this.selectedMenu.length > 0){
          if(this.selectedMenu[0].isRoot){
            this.$Message.warning('目录节点下不能添加资源！');
          }else{
            this.isResEdit = false;
            this.addResource = true;
          }
        }else{
          this.$Message.warning('请先选择一个菜单！');
        }
      },
      //根据名称搜索资源
      searchRes(){
        let data = this.allTableData;
        let reslutData = [];
        let name = this.resourceForm.resourceName;
        if(data.length > 0){
          for(var i=0; i<data.length; i++){
            if(data[i].name.indexOf(name) > -1){
              reslutData.push(data[i]);
            }
          }
        }
        this.tableData = reslutData;
      },
      //添加资源
      saveRes(){
        let formData = this.resFormItem;
        formData["parentId"] = this.selectedMenu[0].id;
        formData["type"] = formData.resourceType;
        formData["router"] = formData.routerName;
        this.$refs.resFormItem.validate((valid) => {
          if (valid) {
            this.$Loading.start();
            if(this.isResEdit){
              this.updateMenuOrRes(formData, 'res')
            }else {
              this.addMenuOrRes(formData, 'res');
            }
          }
        })
      },
      //清空并关闭form面板
      cancelRes(){
        this.$refs['resFormItem'].resetFields();
        this.addResource = false;
      },
      //编辑资源或按钮
      handleEditRes(){
        if(this.selectRowData != ''){
          this.addResource = true;
          this.isResEdit = true;
          this.resFormItem = this.selectRowData;
        }else{
          this.$Message.warning('请选择一条记录修改！');
        }
      },
      //删除资源或按钮
      delResource(){
        if(this.selectRowData != ''){
          let id = this.selectRowData.id;
          this.delMenuOrRes(id,'res');
        }else{
          this.$Message.warning('请选择一条记录删除！');
        }
      }
    },
    created(){
      this.getTreeDataList();
    }
  }
</script>
